package fcnet

import (
	"bytes"
	"encoding/binary"
	"errors"

	"gitee.com/fcsvr/fancy/fclog"
	"gitee.com/fcsvr/fancy/utils"
)

type Pack struct {
}

func NewPack() *Pack {
	return &Pack{}
}

func (this *Pack) GetHeadLen() uint8 {
	return HEAD_LEN
}

func (this *Pack) Pack(msg *Msg) ([]byte, error) {
	dataBuff := bytes.NewBuffer([]byte{})

	if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetHead()); err != nil {
		return nil, err
	}

	if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetHeadEx()); err != nil {
		return nil, err
	}

	if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetData()); err != nil {
		return nil, err
	}
	return dataBuff.Bytes(), nil
}

func (this *Pack) Unpack(data []byte) (*Msg, error) {
	dataBuff := bytes.NewReader(data)

	msg := &Msg{}
	if err := binary.Read(dataBuff, binary.LittleEndian, &msg.Head); err != nil {
		return nil, err
	}

	fclog.Debug("Pack Unpack datalen = %v", msg.DataLen)
	if utils.G_Data.MaxPacketSize > 0 && msg.DataLen > utils.G_Data.MaxPacketSize {
		return nil, errors.New("Too large msg data received")
	}

	return msg, nil
}
